var $userList = $('#userList');
var $organizationList = $('#organizationList');
var leftTreeSelectedNode = '';

var PATH_PREFIX = "";

function setPathPrefix(path) {
	PATH_PREFIX = path;
}

$(function() {
	
	$("#userListWrap").width(($(window).width() - $("#orgTreeWrap").width() - 60) + "px");
	
	$(window).resize(function() {
		$("#userListWrap").width(($(window).width() - $("#orgTreeWrap").width() - 60) + "px");
	});
	
	ajaxRefreshUserList();
	
	$("#empStat").select2();
	
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();
	
	// 初始化组织树
	$organizationList.jstree(
		{
			'core' : {
				'animation' : 0,
				"check_callback" : true,
				'data' : {
					'url' : ctx + 'sys/user/ajaxOrganizationList.do',
					'cache' : false,
					'data' : function(node) {
						var nodeId = '';
						if (node.id) {
							nodeId = node.id.replace('#', '');
						}
						return {
							'orgId' : nodeId
						};
					}
				},
				"themes" : {
					"name" : "default",
					"dots" : false,
					"icons" : false
				}
			},
			'contextmenu' : {
				'items' : function(node) {
					var id = $(node).attr('id') || '';
					if(id.indexOf('FIRM-') != -1) {  // 公司
						var tmp = {
								'modify' : {}
							};
							tmp.modify.label = "修改机构扩展信息";
							tmp.modify.action = function(data) {
								var inst = $.jstree.reference(data.reference);
								var obj = inst.get_node(data.reference);
								var id = $(obj).attr('id');  // , parent = $(obj).attr('parent');
								modifyFirmExtInfo(id);
							};
							return tmp;
					} else {
						return {};
					}
				}
			},
			'plugins' : [ 'wholerow', "contextmenu" ]
		}
	).bind('click.jstree', function(event) {
		var eventNodeName = event.target.nodeName;
		if (eventNodeName == 'I') {
			return;
		} else if (eventNodeName == 'A') {
			var $subject = $(event.target).parent();
//			if ($subject.find('ul').length > 0) {
//			} else {
				//选择的id值
				queryByCondtionTree($(event.target).parents('li').attr('id'));
//			}
		}  
	});
});

/**
 * 刷新用户列表
 * @returns
 */
function ajaxRefreshUserList() {
	$userList.jqGrid({
        url: PATH_PREFIX + 'userListPage.do',
        caption: '用户查询列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',
        datatype: "json",        
		colNames:['ID', "账号", "姓名", "empType", "类型", "邮箱", "stat", "状态", '操作'],        
		colModel:[
                    {name:'empID',index:'empID',align:'center',hidden:true, key:true,sortable:false},              
                    {name:'login',index:'login', width:40, resizable:true,align:'left',sortable:false},
					{name:'empName',index:'empName', width:40, resizable:true,align:'left',sortable:false},
					{name:'empType',index:'empType', hidden: true},
					{name:'empTypeNm',index:'empTypeNm',width:50, resizable:true,align:'left', sortable:false},
					{name:'empEmail',index:'empEmail',width:50, resizable:true,align:'left', sortable:false},
					{name:'empStat',index:'empStat', hidden: true},
					{name:'empStatNm',index:'empStatNm', width:20, resizable:true,align:'left',sortable:false},
					{name:'option',index:'option', width: 30, resizable:true,align:'left',sortable:false}
				 ],     
        rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: {
        	        search: "search", 
        	        page: "pageNo",
        	        rows: "limit" 
        	       },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },
        multiselect: false,
        pager: "#userPage",
        viewrecords: true,
        hidegrid: false,
        gridComplete: function() {
            var ids = $userList.jqGrid('getDataIDs');
			for(var i = 0; i < ids.length; i++){
                var rowId = ids[i];
                var rowData = $userList.jqGrid('getRowData', rowId);
                
                var empType = rowData.empType;
                var stat = rowData.empStat;
                
                var ac = '';
                var iv = '';
                
                if(stat == 'STAR') {
                	ac = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Active" name="'+ rowId +'Active" title="激活" disabled="disabled" >激活</a>';
                	iv = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Invalid" name="'+ rowId +'Update" title="注销" onclick="userInvalid(\''+rowId+'\', \''+empType+'\');" >注销</a>';
                } else if(stat == 'STOP') {
                	ac = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Active" name="'+ rowId +'Active" title="激活" onclick="userActive(\''+rowId+'\', \''+empType+'\');" >激活</a>';
                	iv = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Invalid" name="'+ rowId +'Update" title="注销" disabled="disabled" >注销</a>';
                } else {
                	ac = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Active" name="'+ rowId +'Active" title="激活" disabled="disabled" >激活</a>';
                	iv = '<a date-rowid="' + rowId + '" href="javascript:;" class="btn btn-link btn-jqgrid" id="'+ rowId +'Invalid" name="'+ rowId +'Update" title="注销" disabled="disabled" >注销</a>';
                }
                $userList.jqGrid('setRowData',ids[i],{option:ac + iv});
			}	
		}			
	});
	$userList.navGrid('#userPage', { edit: false, add: false, del: false, search: false, refreshstate: 'current' });
    $userList.jqGrid('setFrozenColumns');
    jqGridResize($userList);
}

function modifyFirmExtInfo(firmId) {
	if(firmId.indexOf("-IN") != -1) {
		ctools.alert("操作失败", "不允许在此处对内部机构进行操作", "warning");
		return;
	}
	var actionUrl = "/solution/sys/organization/modifyFirmExtInfoView.do?firmId=" + firmId;
	window.open(actionUrl);
}

function queryByCondtionTree(nodeId) {
	leftTreeSelectedNode = nodeId;
	queryByCondtion(true);
}

function queryByCondtion(flag) {
	var nodeId = leftTreeSelectedNode;
	
	var login = $.trim($("#login").val());   
    var empEmail = $.trim($("#empEmail").val());  
    var emName = $.trim($("#emName").val());  
    var empStat = $.trim($("#empStat").val());
    if(!nodeId) {
    	nodeId = '';
    }
    
    var postData = $userList.jqGrid("getGridParam", "postData");
    $.extend(postData, {
    	'sp[nodeId]':nodeId,
        'sp[login]':login,
        'sp[empEmail]':empEmail,
        'sp[emName]':emName,
        'sp[empStat]':empStat
    });
    if (flag) {
    	$userList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	$userList.jqGrid("setGridParam",{"datatype": "json"}).trigger("reloadGrid"); //重新载入Grid表格
    }
};

function userActive(empId, empType) {
	if(empType == 'IN') {
		ctools.alert("操作失败", "不允许在此处对内部员工进行操作", "warning");
		return;
	}
	swal({
		title : "您确定要激活此用户吗?",
		text : "",
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#fc6821",
		confirmButtonText : "是",
		cancelButtonText : "否",
		closeOnConfirm : false,
		closeOnCancel : true
	}, function(isConfirm) {
		if (isConfirm) {
			var actionUrl = PATH_PREFIX + "changeEmpStat.do?empId=" + empId + "&stat=STAR";
			$.ajax({
				type: 'POST',
				url: actionUrl,
				success: function(data){
					swal("操作成功!", "", "success");
					queryByCondtion(false);
				},
				error:function(xhr){
				   sweetAlertAjaxError(xhr);
				}
			});
		}
	});
}
function userInvalid(empId, empType) {
	if(empType == 'IN') {
		ctools.alert("操作失败", "不允许在此处对内部员工进行操作", "warning");
		return;
	}
	swal({
		title : "您确定要注销此用户吗?",
		text : "",
		type : "warning",
		showCancelButton : true,
		confirmButtonColor : "#fc6821",
		confirmButtonText : "是",
		cancelButtonText : "否",
		closeOnConfirm : false,
		closeOnCancel : true
	}, function(isConfirm) {
		if (isConfirm) {
			var actionUrl = PATH_PREFIX + "changeEmpStat.do?empId=" + empId + "&stat=STOP";
			$.ajax({
				type: 'POST',
				url: actionUrl,
				success: function(data){
					swal("操作成功!", "", "success");
					queryByCondtion(false);
				},
				error:function(xhr){
				   sweetAlertAjaxError(xhr);
				}
			});
		}
	});
}

function outOrgAddView() {
	var actionUrl = "/solution/sys/organization/outOrgAddView.do";
	window.open(actionUrl);
}

function outUserAddView() {
	var actionUrl = PATH_PREFIX + "outUserAddView.do";
	window.open(actionUrl);
}

function clickRefresh() {
	var actionUrl = ctx + "utils/cached/shareCached/refreshShareCached.do";
	openDialog(actionUrl);
}

//绑定回车事件,查询
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});